package mspbots.data.sync.jira.receivers;

import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.data.sync.BaseReceiver;
import mspbots.data.sync.ResultMessageModel;
import mspbots.data.sync.jira.model.JiraUser;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;

/**
 * @author Jay Yang
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class JiraUserReceiver extends BaseReceiver {

    @RabbitListener(queues = "jira.user.sync")
    public void process(ResultMessageModel model) {
        if (ObjectUtils.isEmpty(model.getEntity()) || !ResultMessageModel.MessageModelAction.ADD.equals(model.getAction())) {
            log.error("jira.user.sync entry is null,or Action No Add");
            return;
        }

        JsonNode node = model.getEntity();
        JiraUser data = JiraUser.builder().otherId(node.get("key").asText()).build();
        data.setExtend(node);
        data.setTenantId(model.getTenantId());
        data.setSyncTime(LocalDateTime.now());

        this.databaseClient.execute("SELECT id FROM jira_user WHERE tenant_id =:tenantId AND other_id =:otherId")
                .as(Long.class)
                .bind("tenantId", data.getTenantId())
                .bind("otherId", data.getOtherId())
                .fetch().one()
                .flatMap(id -> {
                    data.setId(id);
                    return this.databaseClient.update().table(JiraUser.class).using(data).fetch().rowsUpdated();
                })
                .switchIfEmpty(this.databaseClient.insert().into(JiraUser.class).using(data).fetch().rowsUpdated())
                .subscribe(result -> log.debug("JiraUser save is success {}", result),
                        err -> log.error("JiraUser save or update is error,msg: {}", err.getMessage()));
    }
}
